package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.LikeAdminThreadLocal;
import com.mdd.admin.service.ILegalLawyerService;
import com.mdd.admin.validate.LegalLawyerCreateValidate;
import com.mdd.admin.validate.LegalLawyerSearchValidate;
import com.mdd.admin.validate.LegalLawyerStateUpdateValidate;
import com.mdd.admin.validate.LegalLawyerUpdateValidate;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.vo.LegalLawyerDetailVo;
import com.mdd.admin.vo.LegalLawyerListedVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.LegalLawyer;
import com.mdd.common.mapper.LegalLawyerMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 律师列表实现类
 * @author LikeAdmin
 */
@Service
public class LegalLawyerServiceImpl implements ILegalLawyerService {
        
    @Resource
    LegalLawyerMapper legalLawyerMapper;

    /**
     * 律师列表列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<LegalLawyerListedVo>
     */
    @Override
    public PageResult<LegalLawyerListedVo> list(PageValidate pageValidate, LegalLawyerSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        MPJQueryWrapper<LegalLawyer> mpjQueryWrapper = new MPJQueryWrapper<>();
        mpjQueryWrapper.selectAll(LegalLawyer.class).select("t2.name as areaName, t4.real_name as cooperatorName, t5.nickname as salesmanName")
                .leftJoin("legal_areas t2 on t2.id = t.a_id")
                .leftJoin("legal_cooperation_bind t3 on t3.creditor_user_id = t.user_id")
                .leftJoin("la_user t4 on t4.id = t3.cooperator_user_id")
                .leftJoin("business_user t5 on t5.id = t.salesman")
                .orderByAsc("t.id");

        if (StringUtils.isNotEmpty(searchValidate.getKeyword())) {
            String keyword = searchValidate.getKeyword();
            mpjQueryWrapper.nested(wq->wq
                    .like("t.realname", keyword).or()
                    .like("t.mobile", keyword));
        }

        legalLawyerMapper.setSearch(mpjQueryWrapper, searchValidate, new String[]{
                "=:status@t.status:int"
        });

        IPage<LegalLawyerListedVo> iPage = legalLawyerMapper.selectJoinPage(
                new Page<>(page, limit), LegalLawyerListedVo.class, mpjQueryWrapper);
        return PageResult.iPageHandle(iPage);
    }

    /**
     * 律师列表详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return LegalLawyer
     */
    @Override
    public LegalLawyerDetailVo detail(Integer id) {
        Long count = legalLawyerMapper.selectCount(
                new QueryWrapper<LegalLawyer>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.isTrue(count != 0, "数据不存在");

        MPJQueryWrapper<LegalLawyer> mpjQueryWrapper = new MPJQueryWrapper<>();
        mpjQueryWrapper.selectAll(LegalLawyer.class).select("t2.name as areaName")
                .leftJoin("legal_areas t2 on t2.id = t.a_id")
                .eq("t.id", id)
                .last("limit 1");
        return legalLawyerMapper.selectJoinOne(LegalLawyerDetailVo.class, mpjQueryWrapper);
    }

    /**
     * 律师列表新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(LegalLawyerCreateValidate createValidate) {
        LegalLawyer model = new LegalLawyer();
        model.setAId(createValidate.getAId());
        model.setUserId(createValidate.getUserId());
        model.setRealname(createValidate.getRealname());
        model.setAvatar(UrlUtils.toRelativeUrl(createValidate.getAvatar()));
        model.setGender(createValidate.getGender());
        model.setIdNumber(createValidate.getIdNumber());
        model.setMobile(createValidate.getMobile());
        model.setLawOffice(createValidate.getLawOffice());
        model.setLawOfficeAddress(createValidate.getLawOfficeAddress());
        model.setCityId(createValidate.getCityId());
        model.setAreaId(createValidate.getAreaId());
        model.setWorkBeginDate(createValidate.getWorkBeginDate());
        model.setWorkYears(createValidate.getWorkYears());
        model.setJobType(createValidate.getJobType());
        model.setLawyerCertFiles(createValidate.getLawyerCertFiles());
        model.setOtherCertFiles(createValidate.getOtherCertFiles());
        model.setIdCardFiles(createValidate.getIdCardFiles());
        model.setSkilledField(createValidate.getSkilledField());
        model.setBusinessScope(createValidate.getBusinessScope());
        model.setStatus(createValidate.getStatus());
        model.setRefuseRemark(createValidate.getRefuseRemark());
        model.setDeletedAt(createValidate.getDeletedAt());
        model.setCheckTime(createValidate.getCheckTime());
        model.setCheckUser(createValidate.getCheckUser());
        model.setCommissionRate(createValidate.getCommissionRate());
        model.setCreatedAt(createValidate.getCreatedAt());
        model.setLinkAddress(createValidate.getLinkAddress());
        model.setLawyerCertNumber(createValidate.getLawyerCertNumber());
        model.setSalesman(createValidate.getSalesman());
        legalLawyerMapper.insert(model);
    }

    /**
     * 律师列表编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(LegalLawyerUpdateValidate updateValidate) throws ParseException {
        LegalLawyer model = legalLawyerMapper.selectOne(
                new QueryWrapper<LegalLawyer>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        Date workBeginDate = new SimpleDateFormat("yyyy-MM-dd")
                .parse(updateValidate.getWorkBeginDate());
        int days = TimeUtils.datePoorDay(new Date(), workBeginDate);

        model.setRealname(updateValidate.getRealname());
        model.setGender(updateValidate.getGender());
        model.setIdNumber(updateValidate.getIdNumber());
        model.setMobile(updateValidate.getMobile());
        model.setLawOffice(updateValidate.getLawOffice());
        model.setLawOfficeAddress(updateValidate.getLawOfficeAddress());
        model.setWorkBeginDate(workBeginDate);
        model.setWorkYears(new BigDecimal((double) days/356).setScale(2, BigDecimal.ROUND_HALF_UP));
        model.setJobType(updateValidate.getJobType());
        model.setLawyerCertFiles(updateValidate.getLawyerCertFiles());
        model.setOtherCertFiles(updateValidate.getOtherCertFiles());
        model.setIdCardFiles(updateValidate.getIdCardFiles());
        model.setSkilledField(updateValidate.getSkilledField());
        model.setBusinessScope(updateValidate.getBusinessScope());
        model.setSalesman(updateValidate.getSalesman());
        legalLawyerMapper.updateById(model);
    }

    @Override
    public void editStatus(LegalLawyerStateUpdateValidate updateValidate) {
        LegalLawyer model = legalLawyerMapper.selectOne(
                new QueryWrapper<LegalLawyer>()
                        .eq("id",  updateValidate.getId())
                        .last("limit 1"));
        Assert.notNull(model, "数据不存在!");

        String adminId = LikeAdminThreadLocal.get("adminId").toString();
        model.setStatus(updateValidate.getStatus());
        model.setCheckTime(new Date());
        model.setCheckUser(Long.parseLong(adminId));
        legalLawyerMapper.updateById(model);
    }

    /**
     * 律师列表删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        LegalLawyer model = legalLawyerMapper.selectOne(
                new QueryWrapper<LegalLawyer>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        legalLawyerMapper.delete(new QueryWrapper<LegalLawyer>().eq("id", id));
    }

}
